<template>
  <el-card shadow="never">
    <template #header>
      <div class="card-header">
        <el-form :inline="true" :model="params.entity" style="padding-bottom: 0px;">
          <el-form-item label="角色名称">
            <el-input v-model="params.entity.roleName" placeholder="角色名称"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search"  @click="searchData">查询</el-button>
            <el-button type="primary" :icon="Plus" @click="addDialog">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <el-table
        v-loading="loading"
        :data="tableData.list" style="width: 100%" height="500"
        :default-sort="{ prop: 'date', order: 'descending' }" @selection-change="handleSelectionChange">
      <el-table-column fixed type="selection" width="55"/>
      <!-- <el-table-column prop="id" label="编号" width="60"/> -->
      <el-table-column prop="roleName" label="角色名称" width="160" show-overflow-tooltip/>
      <el-table-column prop="roleIntro" label="介绍" show-overflow-tooltip/>
      <el-table-column prop="createUserName" label="创建人" width="160" show-overflow-tooltip/>
      <el-table-column prop="createTime" label="创建时间"  width="160"  show-overflow-tooltip/>
      <!-- <el-table-column prop="updateTime" label="更新时间" /> -->
      <el-table-column prop="remark" label="备注" width="160" show-overflow-tooltip/>
      <el-table-column fixed="right" label="操作" width="300" show-overflow-tooltip>
        <template #header>
          <el-input v-model="params.search" @keyup.enter.native="searchData" placeholder="搜索角色名称/介绍"/>
        </template>
        <template #default="scope">
          <el-button link type="danger" :icon="Delete" size="small" @click="showDeleteDialog(scope.row.id)">删除</el-button>
          <el-button link type="primary" :icon="Edit" size="small" @click="editDialog(scope.row)">编辑</el-button>
          <el-button link type="primary" :icon="Setting" size="small" @click="allotPermitDialog(scope.row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination v-model:currentPage="params.current" v-model:page-size="params.size"
                   :page-sizes="[100, 200, 300, 400]" layout="sizes, prev, pager, next" :total="tableData.total"
                   @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </el-card>

  <!-- 新增或者修改页面-->
  <RoleAddOrEdit @closeEditDialog="closeEditDialog"
                 :addOrEditVisible="addOrEditVisible"
                 :ruleForm="ruleForm"
                 :addDataType="addDataType"
  ></RoleAddOrEdit>

  <role-permit-tree-dialog
      :allotPermitVisible="allotPermitData.allotPermitVisible"
      :tableData="allotPermitData.tableData"
      :checkedKeys="allotPermitData.checkedKeys"
      :roleId="allotPermitData.roleId"
      @closeAllotPermitDialog="closeAllotPermitDialog"
      @submitAlotPermit="submitAlotPermit"
  >
  </role-permit-tree-dialog>
</template>

<script lang="ts" setup>
import {ElTable, ElMessage, ElMessageBox} from 'element-plus'
import {onMounted, computed, reactive, ref} from 'vue'
import {Params} from "@/apis/model/common/common.interfaces"
import {Delete, Edit, Search, Share, Upload, Plus, Setting } from '@element-plus/icons-vue'
import RoleAddOrEdit from './RoleAddOrEdit.vue'
import {Role, RolePermitTree} from "@/apis/model/system/RoleModel";
import {deleteRoleById, rolePage} from "@/apis/http/system/RoleHttp";
import {listPermitIdByRoleId, savePermitByRoleId} from "@/apis/http/system/PermitHttp";
import RolePermitTreeDialog from "@/views/system/role/RolePermitTreeDialog.vue";
// 查询
const params: Params = reactive({
  current: 1,
  size: 10,
  search: '',
  entity: {} as Role
})

const ruleForm = ref<Role>({} as Role)
// AddOrEditVisible
const addOrEditVisible = ref(false)

// 分配权限
const allotPermitData = reactive<RolePermitTree>({
  allotPermitVisible:false,   // dialog 是否显示
  tableData : [] ,
  checkedKeys: [],
  roleId: -1
})

// table 表数据
const tableData: any = ref({});
// 加载数据
const loading = ref(true)
const addDataType = ref('add');

/**
 * 初始化数据
 */
const initList = () => {
  loading.value = true
  rolePage(params).then(res => {
    const code = res.code
    const message = res.message
    const data = res.data
    if (code == 200) {
      tableData.value = data
    }
    loading.value = false
  })
}

/**
 * search 查询数据
 */
const searchData = () => {
  initList()
}

/**
 * 每页数据量改变查询数据
 * @param val
 */
const handleSizeChange = (val: number) => {
  params.size = val
  initList()
}

/**
 * 分页查询数据
 * @param val
 */
const handleCurrentChange = (val: number) => {
  params.current = val
  initList()
}

/**
 * 添加弹出
 */
const addDialog = () => {
  addOrEditVisible.value = true
  ruleForm.value = {} as Role
  addDataType.value = 'add'
}

//修改弹窗
const editDialog = (row: Role) => {
  addOrEditVisible.value = true
  ruleForm.value = row
  addDataType.value = 'edit'
}

// 关闭修改弹窗
const closeEditDialog = (e: any) => {
  addOrEditVisible.value = e.addOrEditVisible
  if(e.refushList = true) {
    params.current = 1;
    initList();
  }
}

// 分配权限弹窗
const allotPermitDialog = async (row: Role) => {
  allotPermitData.allotPermitVisible = true
  allotPermitData.roleId = row.id
  allotPermitData.checkedKeys = [];
  allotPermitData.tableData = [];
  await listPermitIdByRoleId(row.id).then(res => {
    const code = res.code
    const message = res.message
    const data = res.data
    if (code == 200) {
      allotPermitData.checkedKeys = data.checkPermit;
      allotPermitData.tableData = data.permitTrees
    }
  })
}

// 关闭权限弹窗
const closeAllotPermitDialog = (e: RolePermitTree) => {
  allotPermitData.allotPermitVisible = e.allotPermitVisible
}

const submitAlotPermit = (e: RolePermitTree) =>{
  allotPermitData.allotPermitVisible = e.allotPermitVisible
  let checkedKeys = e.checkedKeys
  savePermitByRoleId({
    roleId: e.roleId,
    permitIds: checkedKeys
  }).then(res =>{
    const code = res.code
    const message = res.message
    const data = res.data
    if (code == 200) {
      ElMessage({
        message: '分配权限成功',
        type: 'success',
      })
      // 刷新数据
      initList()
    }
  })
}

/**
 * 弹出删除对话框
 */
const showDeleteDialog = (id: number) => {
  ElMessageBox.confirm(
      '是否删除角色?',
      '提醒',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        deleteRoleById(id).then(res => {
          const code = res.code;
          if (code == 200) {
            ElMessage({
              message: '删除数据成功！',
              type: 'success',
            })
            initList();
          } else {
            ElMessage.error('删除数据失败！');
          }
        })
      })
      .catch(() => {
        // ElMessage({
        //   type: 'info',
        //   message: 'Delete canceled',
        // })
      })
}

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<Role[]>([])
const toggleSelection = (rows?: Role[]) => {
  if (rows) {
    rows.forEach((row) => {
      multipleTableRef.value!.toggleRowSelection(row, undefined)
    })
  } else {
    multipleTableRef.value!.clearSelection()
  }
}
const handleSelectionChange = (val: Role[]) => {
  multipleSelection.value = val
}

onMounted(() => {
  initList()
})
</script>

<style>
</style>
